package com.hackaton.discounts;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListAdapter extends BaseAdapter{
    
	private ArrayList<Discount> data;
	private Activity activity;
	private static LayoutInflater inflater=null;
	private AssetManager assetManager;
	private Bitmap bitmap;
	BufferedInputStream buf;
	FileInputStream stream;
	BitmapFactory bitmapFactoty;
	
	public static class ViewHolder{
		public ImageView image;
		public TextView tvTitle;
		public TextView tvDetails;
	}
	public ListAdapter(Activity activity, ArrayList<Discount> data){
		this.data=data;
		this.activity=activity;
		inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		assetManager=activity.getAssets();
	}
	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view=convertView;
		ViewHolder holder;
		if(convertView==null){
			view=inflater.inflate(R.layout.list_item, null); 
			holder=new ViewHolder();
			holder.image=(ImageView)view.findViewById(R.id.imgItemImage);
			holder.tvTitle=(TextView)view.findViewById(R.id.tvItemTitle);
			holder.tvDetails=(TextView)view.findViewById(R.id.tvItemDetails);
			view.setTag(holder);
		}
		else
			holder=(ViewHolder)view.getTag();
		    holder.tvTitle.setText(data.get(position).title);
		    holder.tvDetails.setText(data.get(position).text);
		    try {
				stream=(FileInputStream) assetManager.open(data.get(position).imgUri);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    buf=new BufferedInputStream(stream);
		    bitmap=bitmapFactoty.decodeStream(stream);
		    holder.image.setImageBitmap(bitmap);
		return view;
	}

}
